<script setup lang="ts">
import axios from "axios";
import qs from "qs";
import $aes from "utils/AES.js";
import { computed, onBeforeMount, onMounted, ref } from "vue";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
const router = useRouter();
const activeIndex = ref("-1");
const username = ref("");
const password = ref("");
const verify = ref("");
const imgSrc = ref("");
const showPwd = ref(false);
const checked = ref(false);
onBeforeMount(() => {
  window.localStorage.removeItem("auth");
  window.localStorage.removeItem("KS_USERROLES");

  //判断本地缓存是否有用户名和密码
  const loginStorage: any = localStorage.getItem("KS_LOGIN_INFO");
  const loginInfo = JSON.parse(loginStorage);

  if (loginInfo) {
    username.value = loginInfo.uname;
    password.value = loginInfo.pwd;
    checked.value = true;
  }

  // TODO 正式版升级时需要去掉
  username.value = "administrator"; //账号
  password.value = "wjjld@Wj2022Zhjt"; //密码 - 单点登录
});
onMounted(() => {
  window.addEventListener("keydown", keyDown);
  getVerifyCode();
});
const keyDown = (e: any) => {
  if (e.keyCode == 13) {
    ToSignIn(); // 定义的登录方法
  }
};
const iconClick = () => {
  showPwd.value = !showPwd.value;
};
const getVerifyCode = () => {
  imgSrc.value =
    import.meta.env.VITE_APP_USER +
    "/captcha/generatecommon" +
    "?" +
    Math.random();
};
const handleRememberPwd = () => {
  if (checked.value) {
    const loginInfo = {
      uname: username.value,
      pwd: password.value,
    };
    localStorage.setItem("KS_LOGIN_INFO", JSON.stringify(loginInfo));
  } else {
    localStorage.removeItem("KS_LOGIN_INFO");
  }
};
const ToSignIn = () => {
  if (!username.value) {
    message.warning("请输入用户名");
    return false;
  }
  if (!password.value) {
    message.warning("请输入密码");
    return false;
  }
  if (!verify.value) {
    message.warning("请输入验证码");
    return false;
  }
  console.info(this);
  const obj = {
    username: $aes.encrypt(username.value),
    password: $aes.encrypt(password.value),
    captcha: verify.value,
  };

  const param = qs.stringify(obj);
  axios
    .post(import.meta.env.VITE_APP_USER + "/login", param)
    .then((res) => {
      if (res.data.code == 200) {
        // 处理记住密码
        handleRememberPwd();

        // this.SET_ROLES([]);

        // if (window.localStorage.getItem("redirect") != null) {
        //   // 路由来源：上次访问地址
        //   // this.$router.push(window.localStorage.getItem("redirect"));
        //   router.push(window.localStorage.getItem("redirect") as string);
        // } else {
        //   this.$router.push("/index");

        fetchToken();
        router.push("/pcdocument/table");
        // }
      } else {
        message.error(res.data.msg);
        getVerifyCode();
      }
    })
    .catch((error) => {
      message.error(error.response.data.msg);
    });
  // this.$router.push("/pcdocument");
};
const beforeDestroy = () => {
  window.removeEventListener("keydown", keyDown);
};
type authType = {
  access_token: string;
  token_type: string;
  refresh_token: string;
};
function getAuth(): authType {
  const auth = localStorage.getItem("auth");
  return JSON.parse(auth as string);
}
function fetchToken() {
  const url = window.location.toString();
  if (!url.includes("code")) {
    getAuthorizeUri();
  }
}
const oauth_server = import.meta.env.VITE_APP_USER;
const client_uri = import.meta.env.VITE_APP_BACK + "/back";
// Appid
const client_id = "ffzX824G9G"; //线上
function getAuthorizeUri() {
  //回调
  return (window.location.href =
    oauth_server +
    "/oauth2/authorize?response_type=code&client_id=" +
    client_id +
    "&scope=openid&redirect_uri=" +
    client_uri);
}
function saveAuth(sResponse: authType) {
  localStorage.setItem("auth", JSON.stringify(sResponse));
}
</script>

<template>
  <div id="login">
    <div>
      <div class="title">
        <img src="./images/title.png" alt />
      </div>
      <div class="login-box">
        <div class="login-title">
          <span>用户登录</span>
        </div>
        <form class="login-form">
          <div class="input-box" :class="{ 'active-box': activeIndex == '1' }">
            <i class="iconfont before-i icon-yonghu"></i>
            <input
              type="text"
              name="username"
              v-model="username"
              @focus="activeIndex = '1'"
              @blur="activeIndex = '-1'"
              placeholder="请输入用户名"
              autocomplete="off"
            />
          </div>
          <div class="input-box" :class="{ 'active-box': activeIndex == '2' }">
            <i class="iconfont before-i icon-mima"></i>
            <input
              :type="showPwd ? 'text' : 'password'"
              name="password"
              v-model="password"
              @focus="activeIndex = '2'"
              @blur="activeIndex = '-1'"
              placeholder="请输入密码"
              autocomplete="new-password"
            />
            <i
              :class="[
                'iconfont',
                'after-i',
                showPwd ? 'icon-zhengyan1' : 'icon-biyan',
              ]"
              @click="iconClick()"
            ></i>
          </div>
          <div
            class="input-box verify-box"
            :class="{ 'active-box': activeIndex == '3' }"
          >
            <i class="iconfont before-i icon-yanzhengma"></i>
            <input
              type="text"
              name="verify"
              v-model="verify"
              @focus="activeIndex = '3'"
              @blur="activeIndex = '-1'"
              placeholder="请输入验证码"
              autocomplete="off"
            />
            <img :src="imgSrc" alt @click="getVerifyCode" />
          </div>
          <div class="remember-box">
            <input type="checkbox" />
            <span>记住密码</span>
          </div>
          <div class="btn-box">
            <button type="button" @click="ToSignIn">立即登录</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
#login {
  // position: absolute;
  // top: 0px;
  // left: 0;
  // bottom: 0;
  width: 100%;
  height: 100%;
  background-image: url(./images/bg_ks.png);
  background-size: 100% 100%;
  padding: 60px 0px 130px;
  & > div {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .title {
      width: 810px;
      margin-right: 153px;
      // margin-bottom: 70px;
      img {
        width: 100%;
      }
    }
    .login-box {
      width: 600px;
      border-radius: 4px;
      background-image: url(./images/login_bg.png);
      background-size: 100% 100%;
      // box-shadow: 0px 0px 10px 2px rgba(0, 0, 0, 0.12);
      padding: 40px 60px 80px;
      .login-title {
        padding-bottom: 15px;
        margin-bottom: 60px;
        // border-bottom: 1px solid #eee;
        span {
          display: inline-block;
          color: rgba(0, 0, 0, 0.85);
          font-size: 24px;
          font-weight: 600;
          position: relative;
          letter-spacing: 3px;
          &::after {
            content: "";
            position: absolute;
            bottom: -20px;
            left: 20px;
            height: 10px;
            width: 60px;
            border-radius: 5px;
            background-color: rgba(34, 91, 252, 1);
            box-shadow: 0px 2px 4px 0px rgba(34, 91, 252, 45);
          }
        }
      }
      .login-form {
        .input-box {
          position: relative;
          display: flex;
          margin-top: 30px;
          align-items: center;
          input {
            font-size: 16px;
            width: 100%;
            height: 55px;
            border-radius: 4px;
            border: 1px solid #ddd;
            padding-left: 52px;
            transition: all 0.2s linear;
          }
          .before-i {
            position: absolute;
            left: 15px;
            font-size: 22px;
            color: rgba(0, 0, 0, 0.45);
            transition: all 0.2s linear;
          }
          .after-i {
            position: absolute;
            right: 15px;
            font-size: 22px;
            color: rgba(0, 0, 0, 0.25);
            cursor: pointer;
            transition: all 0.2s linear;
          }
          .after-i:hover {
            color: #0060f4;
          }
        }
        .verify-box {
          input {
            padding-right: 116px;
          }
          img {
            position: absolute;
            right: 8px;
            width: 100px;
            height: 40px;
            cursor: pointer;
          }
        }
        .active-box {
          input {
            box-shadow: 0px 4px 14px 0px rgba(0, 0, 0, 0.05);
            border: 1px solid transparent;
          }
          .before-i {
            color: #0060f4;
          }
        }
        .remember-box {
          display: flex;
          align-items: center;
          margin: 20px 0px 40px;
          input[type="checkbox"] {
            width: 16px;
            height: 16px;
            margin-right: 8px;
            line-height: 16px;
            cursor: pointer;
            border: 1px solid #bbb;
            border-radius: 2px;
            transition: all 0.2s linear;
            background: transparent;
            display: flex;
            align-items: center;
            justify-content: center;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            -ms-appearance: none;
          }
          input[type="checkbox"]:checked {
            content: "";
            color: #fff;
            border: 1px solid #0060f4;
            background: #0060f4;

            &::after {
              content: "\2713";
              font-size: 12px;
            }
          }
          input[type="checkbox"]:hover {
            border: 1px solid #0060f4;
          }
          span {
            font-size: 16px;
            color: rgba(0, 0, 0, 0.85);
          }
        }
        .btn-box {
          button {
            width: 100%;
            height: 55px;
            background: linear-gradient(to left, #225bfc 0%, #6b94f2 100%);
            border-radius: 4px;
            font-size: 18px;
            color: #fff;
            border: none;
            cursor: pointer;
            transition: all 0.2s linear;
            letter-spacing: 2px;
          }
          button:hover {
            opacity: 0.9;
          }
        }
        & > div:first-child {
          margin-top: 0;
        }
      }
    }
  }
}
// @media screen and (min-width: 1400px) and (max-width: 1919px) {
// 	#login {
// 		padding: 60px 0px 70px;
// 		& > div {
// 			.title {
// 				height: 90px;
// 			}
// 			.login-box {
// 				transform: scale(0.9, 0.9);
// 			}
// 		}
// 	}
// }
// @media screen and (min-width: 1024px) and (max-width: 1399px) {
// 	#login {
// 		padding: 40px 0px 50px;
// 		& > div {
// 			.title {
// 				height: 80px;
// 			}
// 			.login-box {
// 				transform: scale(0.85, 0.85);
// 			}
// 		}
// 	}
// }
</style>
